<?php

    /**
     * @package      Modules
     * @subpackage   Base_Classes_IO_Options_Adapter
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    class Base_Classes_IO_Options_Adapter_Resize extends Base_Classes_IO_Options_Adapter_Abstract
    {

     ////////////////////////////////////////////////////////////////////////////
    //                              Methods                                    //
    ////////////////////////////////////////////////////////////////////////////

        /**
         * Process the resizing option.
         *
         * @throws      Core_Exception
         * @param       array       $file
         * @param       string      $originalFileName
         * @param       array       $optionParams      $adapter         
         */
        public function process(array $file, $originalFileName, array $optionParams = array())
        {
            foreach ($optionParams as $resizeKey => $resizeParams) {
                // Opens a stream with original image
                $imageAdapter = Core_Image_Adapter::factory(Core_Image_Adapter::ADAPTER_GD2);
                $imageAdapter->open( Core_IO_Path::combine($file['path'], $originalFileName));

                // Generates new filename
                $newPath	= Core_IO_Path::combine($file['path'], $resizeKey);
                $fileName	= Core_IO_Path::combine($newPath, $originalFileName);
                $size		= explode('x', $resizeParams['size']);

                if (count($size) != 2) {
                    throw new Core_Exception('Fatal error : image size format must be widthxheight');
                }

                // Creates folder if it doesn't exist
                if (!Core_IO_Directory::exists($newPath)) {    
                    Core_IO_Directory::createDirectory($newPath, '0744');
                }

                // Deletes file if it already exists
                if (Core_IO_File::exists($fileName)) {
                    Core_IO_File::delete($fileName);
                }

                // Keeps ratio and fills with a background color if asked
                if (isset($resizeParams['background'])) {
                    $imageAdapter->backgroundColor($resizeParams['background']);
                    $imageAdapter->keepAspectRatio(true);
                    $imageAdapter->keepFrame(true);
                }

                if (isset($resizeParams['quality'])) {
                    $imageAdapter->setQuality($resizeParams['quality']);
                }

                // Creates new image with new dimensions
                $imageAdapter->resize($size[0], $size[1]);
                $imageAdapter->save($fileName);
            }
        }
    }